<template>
  <div class="post-detail-container">
    <!-- 帖子内容 -->
    <el-card class="post-card">
      <div class="post-header">
        <div class="user-info">
          <el-avatar :src="post.authorAvatar" :size="40">{{ post.authorName ? post.authorName.charAt(0) : 'U' }}</el-avatar>
          <div class="user-meta">
            <span class="username">{{ post.authorName }}</span>
            <span class="post-time">{{ post.createTime }}</span>
          </div>
        </div>
        <div class="post-actions" v-if="userInfo && userInfo.id === post.authorId">
          <el-button type="text" @click="handleEdit">编辑</el-button>
          <el-button type="text" class="danger" @click="handleDelete">删除</el-button>
        </div>
      </div>

      <div class="post-content">
        <h2 class="post-title">
          {{ post.title }}
          <el-tag size="small" class="category-tag">{{ getCategoryText(post.category) }}</el-tag>
        </h2>
        <div class="post-text">{{ post.content }}</div>
      </div>

      <div class="post-footer">
        <div class="post-stats">
          <span class="stat-item">
            <i class="el-icon-view"></i>
            {{ post.viewCount }}
          </span>
          <span class="stat-item">
            <i class="el-icon-chat-dot-round"></i>
            {{ post.commentCount }}
          </span>
          <span class="stat-item" @click="handleLike">
            <i :class="['el-icon-star-off', { 'liked': post.liked }]"></i>
            {{ post.likeCount }}
          </span>
        </div>
      </div>
    </el-card>

    <!-- 评论区 -->
    <el-card class="comment-card">
      <div slot="header">
        <span>评论 ({{ post.commentCount }})</span>
      </div>

      <!-- 评论输入框 -->
      <div class="comment-form" v-if="userInfo">
        <el-input
          type="textarea"
          v-model="commentForm.content"
          :rows="3"
          placeholder="写下你的评论..."
          resize="none">
        </el-input>
        <div class="form-actions">
          <el-button type="primary" :loading="submitting" @click="handleComment">发表评论</el-button>
        </div>
      </div>
      <div v-else class="login-tip">
        <el-link type="primary" @click="$router.push('/login')">登录</el-link> 后参与评论
      </div>

      <!-- 评论列表 -->
      <div class="comment-list">
        <div v-if="commentList.length === 0" class="empty-tip">
          暂无评论，快来抢沙发吧！
        </div>
        <div v-else v-for="comment in commentList" :key="comment.id" class="comment-item">
          <div class="comment-user">
            <el-avatar :src="comment.userAvatar" :size="32">{{ comment.username ? comment.username.charAt(0) : 'U' }}</el-avatar>
            <div class="comment-meta">
              <span class="username">{{ comment.username }}</span>
              <span class="comment-time">{{ comment.createTime }}</span>
            </div>
          </div>
          <div class="comment-content">
            <template v-if="comment.parentId">
              <div class="reply-info">
                回复 <span class="reply-user">@{{ comment.parentUsername }}</span>：
              </div>
            </template>
            <p class="comment-text">{{ comment.content }}</p>
          </div>
          <div class="comment-actions">
            <template v-if="userInfo">
              <el-button type="text" size="small" @click="showReplyForm(comment)">回复</el-button>
              <template v-if="userInfo.id === comment.userId">
                <el-button type="text" size="small" @click="handleEditComment(comment)">编辑</el-button>
                <el-button type="text" size="small" class="danger" @click="handleDeleteComment(comment)">删除</el-button>
              </template>
            </template>
          </div>

          <!-- 回复表单 -->
          <div class="reply-form" v-if="showingReplyForm && activeComment === comment.id">
            <el-input
              type="textarea"
              v-model="replyForm.content"
              :rows="2"
              placeholder="写下你的回复..."
              resize="none">
            </el-input>
            <div class="form-actions">
              <el-button size="small" @click="cancelReply">取消</el-button>
              <el-button type="primary" size="small" :loading="submitting" @click="handleReply(comment)">回复</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { getPostDetail, deletePost, likePost, unlikePost } from '@/api/post'
import { getCommentList, createComment, updateComment, deleteComment } from '@/api/post'

export default {
  name: 'PostDetail',
  data() {
    return {
      post: {},
      commentList: [],
      commentForm: {
        content: ''
      },
      replyForm: {
        content: ''
      },
      showingReplyForm: false,
      activeComment: null,
      submitting: false,
      loading: false
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo
    })
  },
  methods: {
    // 获取帖子详情
    fetchPostDetail() {
      const id = this.$route.params.id
      getPostDetail(id).then(response => {
        console.log('帖子详情响应:', response)
        if (response.code === 200 && response.data) {
          this.post = response.data
        } else {
          this.$message.error('获取帖子详情失败: ' + (response.message || '未知错误'))
        }
      }).catch(error => {
        console.error('获取帖子详情失败:', error)
        this.$message.error('获取帖子详情失败: ' + (error.message || '未知错误'))
      })
    },
    // 获取评论列表
    fetchCommentList() {
      const postId = this.$route.params.id
      getCommentList(postId).then(response => {
        console.log('评论列表响应:', response)
        if (response.code === 200 && response.data) {
          this.commentList = response.data
          console.log('设置后的评论列表:', this.commentList)
        } else {
          this.$message.error('获取评论列表失败: ' + (response.message || '未知错误'))
        }
      }).catch(error => {
        console.error('获取评论列表失败:', error)
        this.$message.error('获取评论列表失败: ' + (error.message || '未知错误'))
      })
    },
    // 编辑帖子
    handleEdit() {
      this.$router.push(`/main/forum/${this.post.id}/edit`)
    },
    // 删除帖子
    handleDelete() {
      this.$confirm('确认删除该帖子吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePost(this.post.id)
          .then(response => {
            if (response.code === 200) {
              this.$message.success('删除成功')
              this.$router.push('/main/forum')
            } else {
              this.$message.error('删除失败: ' + (response.message || '未知错误'))
            }
          })
          .catch(error => {
            console.error('删除帖子失败:', error)
            this.$message.error('删除失败: ' + (error.message || '未知错误'))
          })
      }).catch(() => {})
    },
    // 点赞/取消点赞
    handleLike() {
      if (!this.userInfo) {
        this.$message.warning('请先登录')
        return
      }
      const request = this.post.liked ? unlikePost : likePost
      request(this.post.id)
        .then(response => {
          if (response.code === 200) {
            this.post.liked = !this.post.liked
            this.post.likeCount += this.post.liked ? 1 : -1
            this.$message.success(this.post.liked ? '点赞成功' : '取消点赞成功')
          } else {
            this.$message.error((this.post.liked ? '取消点赞' : '点赞') + '失败: ' + (response.message || '未知错误'))
          }
        })
        .catch(error => {
          console.error('点赞操作失败:', error)
          this.$message.error((this.post.liked ? '取消点赞' : '点赞') + '失败: ' + (error.message || '未知错误'))
        })
    },
    // 发表评论
    handleComment() {
      if (!this.commentForm.content.trim()) {
        this.$message.warning('请输入评论内容')
        return
      }
      this.submitting = true
      createComment(this.post.id, this.commentForm)
        .then(response => {
          if (response.code === 200) {
            this.$message.success('评论成功')
            this.commentForm.content = ''
            this.fetchCommentList()
            this.fetchPostDetail() // 更新评论数
          } else {
            this.$message.error('评论失败: ' + (response.message || '未知错误'))
          }
        })
        .catch(error => {
          console.error('评论失败:', error)
          this.$message.error('评论失败: ' + (error.message || '未知错误'))
        })
        .finally(() => {
          this.submitting = false
        })
    },
    // 显示回复表单
    showReplyForm(comment) {
      this.showingReplyForm = true
      this.activeComment = comment.id
      this.replyForm.content = ''
    },
    // 取消回复
    cancelReply() {
      this.showingReplyForm = false
      this.activeComment = null
      this.replyForm.content = ''
    },
    // 提交回复
    handleReply(comment) {
      if (!this.replyForm.content.trim()) {
        this.$message.warning('请输入回复内容')
        return
      }
      this.submitting = true
      const data = {
        content: this.replyForm.content,
        parentId: comment.id,
        postId: this.post.id
      }
      createComment(this.post.id, data)
        .then(response => {
          if (response.code === 200) {
            this.$message.success('回复成功')
            this.cancelReply()
            this.fetchCommentList()
            this.fetchPostDetail() // 更新评论数
          } else {
            this.$message.error('回复失败: ' + (response.message || '未知错误'))
          }
        })
        .catch(error => {
          console.error('回复失败:', error)
          this.$message.error('回复失败: ' + (error.message || '未知错误'))
        })
        .finally(() => {
          this.submitting = false
        })
    },
    // 编辑评论
    handleEditComment(comment) {
      this.$prompt('编辑评论', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: comment.content,
        inputPattern: /.+/,
        inputErrorMessage: '评论内容不能为空'
      }).then(({ value }) => {
        updateComment(comment.id, { content: value })
          .then(response => {
            if (response.code === 200) {
              this.$message.success('修改成功')
              this.fetchCommentList()
            } else {
              this.$message.error('修改失败: ' + (response.message || '未知错误'))
            }
          })
          .catch(error => {
            console.error('修改评论失败:', error)
            this.$message.error('修改失败: ' + (error.message || '未知错误'))
          })
      }).catch(() => {})
    },
    // 删除评论
    handleDeleteComment(comment) {
      this.$confirm('确认删除该评论吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteComment(comment.id)
          .then(response => {
            if (response.code === 200) {
              this.$message.success('删除成功')
              this.fetchCommentList()
              this.fetchPostDetail() // 更新评论数
            } else {
              this.$message.error('删除失败: ' + (response.message || '未知错误'))
            }
          })
          .catch(error => {
            console.error('删除评论失败:', error)
            this.$message.error('删除失败: ' + (error.message || '未知错误'))
          })
      }).catch(() => {})
    },
    // 获取分类文本
    getCategoryText(category) {
      const categoryMap = {
        'EXPERIENCE': '养宠经验',
        'HEALTH': '宠物健康',
        'FUNNY': '宠物趣事',
        'OTHER': '其他'
      }
      return categoryMap[category] || '其他'
    }
  },
  created() {
    this.fetchPostDetail()
    this.fetchCommentList()
  }
}
</script>

<style lang="scss" scoped>
.post-detail-container {
  padding: 20px;

  .post-card {
    margin-bottom: 20px;

    .post-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .user-info {
        display: flex;
        align-items: center;

        .user-meta {
          margin-left: 10px;
          display: flex;
          flex-direction: column;

          .username {
            font-size: 14px;
            color: #303133;
            margin-bottom: 2px;
          }

          .post-time {
            font-size: 12px;
            color: #909399;
          }
        }
      }

      .post-actions {
        .el-button {
          padding: 0 10px;
        }

        .danger {
          color: #F56C6C;
        }
      }
    }

    .post-content {
      .post-title {
        margin: 0;
        margin-bottom: 20px;
        font-size: 20px;
        color: #303133;

        .category-tag {
          margin-left: 10px;
          transform: translateY(-2px);
        }
      }

      .post-text {
        color: #606266;
        font-size: 14px;
        line-height: 1.8;
        white-space: pre-wrap;
      }
    }

    .post-footer {
      margin-top: 30px;
      padding-top: 20px;
      border-top: 1px solid #EBEEF5;

      .post-stats {
        .stat-item {
          margin-right: 20px;
          color: #909399;
          font-size: 13px;
          cursor: pointer;

          i {
            margin-right: 4px;

            &.liked {
              color: #409EFF;
            }
          }

          &:hover {
            color: #409EFF;
          }
        }
      }
    }
  }

  .comment-card {
    .comment-form {
      margin-bottom: 20px;

      .form-actions {
        margin-top: 10px;
        text-align: right;
      }
    }

    .login-tip {
      text-align: center;
      color: #909399;
      padding: 20px 0;
    }

    .comment-list {
      .empty-tip {
        text-align: center;
        color: #909399;
        padding: 20px 0;
      }

      .comment-item {
        padding: 20px 0;
        border-bottom: 1px solid #EBEEF5;

        &:last-child {
          border-bottom: none;
        }

        .comment-user {
          display: flex;
          align-items: center;
          margin-bottom: 10px;

          .comment-meta {
            margin-left: 10px;

            .username {
              font-size: 14px;
              color: #303133;
              margin-right: 10px;
            }

            .comment-time {
              font-size: 12px;
              color: #909399;
            }
          }
        }

        .comment-content {
          padding-left: 42px;

          .reply-info {
            color: #909399;
            font-size: 13px;
            margin-bottom: 5px;

            .reply-user {
              color: #409EFF;
            }
          }

          .comment-text {
            margin: 0;
            color: #606266;
            font-size: 14px;
            line-height: 1.6;
          }
        }

        .comment-actions {
          padding-left: 42px;
          margin-top: 10px;

          .el-button {
            padding: 0;
            margin-right: 15px;

            &.danger {
              color: #F56C6C;
            }
          }
        }

        .reply-form {
          margin-top: 15px;
          padding-left: 42px;

          .form-actions {
            margin-top: 10px;
            text-align: right;

            .el-button {
              margin-left: 10px;
            }
          }
        }
      }
    }
  }
}
</style> 